use std::{
    fs::File,
    io::{BufRead, BufReader},
};

use bevy::{prelude::*, render::color::Color::Rgba};

use crate::{
    ascii::{spawn_ascii_sprite, AsciiSheet},
    TILE_SIZE,
};

pub struct TilemapPlugin;

#[derive(Component, Reflect, Default)]
#[reflect(Component)]
pub struct TileCollider {
    pub will: String,
}

impl Plugin for TilemapPlugin {
    fn build(&self, app: &mut App) {
        app.add_startup_system(setup_tilemap)
            .register_type::<TileCollider>();
    }
}

fn setup_tilemap(mut commands: Commands, ascii: Res<AsciiSheet>) {
    let file = File::open("assets/map/map.txt").unwrap();
    let mut tiles = Vec::new();
    for (y, line) in BufReader::new(file).lines().enumerate() {
        if let Ok(line) = line {
            for (x, chars) in line.chars().enumerate() {
                let tile = spawn_ascii_sprite(
                    &mut commands,
                    &ascii,
                    chars as usize,
                    Rgba {
                        red: 0.9,
                        green: 0.9,
                        blue: 0.9,
                        alpha: 1.0,
                    },
                    Vec3::new(
                        (x as f32) * TILE_SIZE - 1.3,
                        -(y as f32) * TILE_SIZE + 0.5,
                        100.0,
                    ),
                    Vec3::splat(1.0),
                );
                if chars == '#' {
                    commands.entity(tile).insert(TileCollider {
                        will: chars.to_string(),
                    });
                }
                tiles.push(tile);
            }
        }
    }
    commands
        .spawn()
        .insert(Name::new("Map"))
        .insert(Transform::default())
        .insert(GlobalTransform::default())
        .push_children(&tiles);
}
